package com.ontheroad.web.filter;

import com.ontheroad.core.annotation.Token;
import com.ontheroad.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by kedong on 2017/6/21 0021.
 */
public class TokenFilter implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        /**
         * 验证是否需要登录（即是否有token）,默认为所有都需要token，如果不用token的话，需加注解显示指明
         * 没有Token注解 即视为需要登录
         */
        Token token = AnnotationUtils.findAnnotation(method, Token.class);
        if (token == null || !token.needToken()) {
            // 验证token，并将token转化为对应的userID
            logger.debug("---------登录验证");
            String tokenStr = request.getParameter("token");
            logger.debug("--------token:" + tokenStr);

            if(StringUtils.isEmpty(tokenStr)){
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
